//
//  BroadbandIPViewController.m
//  Router
//
//  Created by gejiangs on 15/10/15.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "BroadbandIPViewController.h"
#import "IQKeyboardManager.h"
#import "FixedIPViewController.h"
#import "DynamicIPViewController.h"
#import "ChooseWIFITypeView.h"
#import "DiscoverHelper.h"

@interface BroadbandIPViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *boxView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *notButton;
@property (nonatomic, strong)        UITextField *accountTextField;
@property (nonatomic, strong)        UITextField *passwordTextField;
@property (nonatomic, strong) ChooseWIFITypeView *wifiTypeView;
@property (nonatomic, strong) DiscoverHelper *discoverHelper;

@end

@implementation BroadbandIPViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.discoverHelper = [[DiscoverHelper alloc] init];
    self.title = @"宽带设置";
    
    [self initUI];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)initUI
{
    self.notButton.layer.borderColor = COLOR_BASE.CGColor;
    self.notButton.layer.borderWidth = 1.f;
    self.notButton.layer.cornerRadius = 5.f;
    self.nextButton.layer.cornerRadius = 5.f;
    
    self.boxView.layer.borderColor = COLOR_GRAY.CGColor;
    self.boxView.layer.borderWidth = 0.5f;
    self.boxView.layer.cornerRadius = 5.f;
    
    self.tableView.scrollEnabled = NO;
    
    [self enableKeyboardNotification];
}

-(void)keyboardWillShowKeyHeight:(CGFloat)keyHeight
{
    [super setKeyboardShowView:self.nextButton keyboardHeight:keyHeight];
}

- (IBAction)notButtonClicked:(id)sender
{
    __weak __typeof(self)weakSelf = self;
    [self.wifiTypeView setSelectedBlock:^(NSInteger index) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *vcs = [NSMutableArray arrayWithArray:strongSelf.navigationController.viewControllers];
        [vcs removeLastObject];
        BaseViewController *controller;
        if (index == 0)
        {
            controller = [[BroadbandIPViewController alloc] init];
        }
        else if (index == 1)
        {
            controller = [[FixedIPViewController alloc] init];
        }
        else{
            controller = [[DynamicIPViewController alloc] init];
        }
        [vcs addObject:controller];
        [strongSelf.navigationController setViewControllers:vcs animated:NO];
    }];
    [self.wifiTypeView showInView:self.view];
}

- (IBAction)nextButtonClicked:(id)sender
{
    [self resignAllTextField];
    NSString *account = self.accountTextField.text;
    NSString *passsword = self.passwordTextField.text;
    if ([account checkEmpty])
    {
        [self promptMessage:@"请输入宽带账号!"];
        return;
    }
    
    if ([passsword checkEmpty]) {
        [self promptMessage:@"请输入宽带密码"];
        return;
    }
    
    self.activity = [self startActivityWithTitle:@"正在连接..."];
    WEAKSELF
    [_discoverHelper checkBroadBandConfigWithPPPOEName:account pppoePassword:passsword success:^(BOOL succ, id responseObject, NSString *msg) {
        STRONGSELF
        [strongSelf stopActivityWithActivity:strongSelf.activity title:msg];
        [strongSelf checkInternetIsConnected];
    } failure:^(NSError *error) {
        STRONGSELF
        NSString *failedReason = [error localizedDescription];
        [strongSelf stopActivityWithActivity:strongSelf.activity title:failedReason];
    }];

}

#pragma mark -
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
    }
    
    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UITextField *text = [cell.contentView addTextFieldWithDelegate:self fontSize:17];
    [text makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(5);
        make.bottom.offset(-5);
        make.left.offset(10);
        make.right.offset(-10);
    }];
    
    if (indexPath.row == 0) {
        text.placeholder = @"请输入宽带账号";
        text.returnKeyType = UIReturnKeyNext;
        self.accountTextField = text;
    }else if (indexPath.row == 1){
        text.placeholder = @"请输入宽带密码";
        text.returnKeyType = UIReturnKeyDone;
        text.secureTextEntry = YES;
        self.passwordTextField = text;
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0f;
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self resignAllTextField];
}


- (void)resignAllTextField
{
    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

}

#pragma mark UITextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.accountTextField) {
        [self.passwordTextField becomeFirstResponder];
    }else if (textField == self.passwordTextField){
        [textField resignFirstResponder];
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



#pragma mark -
#pragma mark   Request
- (void)checkInternetIsConnected
{
    WEAKSELF
    [self.discoverHelper discoverWIFISuccess:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObject:%@",responseObject);
        NSString *info = responseObject[@"info"];
        if ([info isEqualToString:@"InterNetConnected"])
        {
            [strongSelf promptMessage:@"网络连接正常!"];
            [self dispatchTimerWithTime:2.0 block:^{
                [strongSelf.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            NSString *type = responseObject[@"type"];
            if ([type isEqualToString:@"linkoff"])
            {
                [strongSelf promptMessage:@"网线没有插入WAN口!"];
            }
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString *failedReason = [error localizedDescription];
        [strongSelf promptMessage:failedReason];
    }];
}


#pragma mark -
#pragma mark   getters and setters
- (ChooseWIFITypeView *)wifiTypeView
{
    if (_wifiTypeView == nil)
    {
        _wifiTypeView = [ChooseWIFITypeView loadViewFromNib];
    }
    return _wifiTypeView;
}
@end
